package vip.xiaonuo.core.config;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.EnumUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectionException;
import org.noear.solon.annotation.Component;
import vip.xiaonuo.common.enums.CommonDeleteFlagEnum;

import java.util.Date;

/**
 * 自定义公共字段自动注入
 *
 * @author xuyuxiang
 * @date 2020/3/31 15:42
 */
@Component
public class CustomMetaObjectHandler implements MetaObjectHandler {

    /** 删除标志 */
    private static final String DELETE_FLAG = "deleteFlag";

    /** 创建人 */
    private static final String CREATE_USER = "createUser";

    /** 创建时间 */
    private static final String CREATE_TIME = "createTime";

    /** 更新人 */
    private static final String UPDATE_USER = "updateUser";

    /** 更新时间 */
    private static final String UPDATE_TIME = "updateTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        try {
            //为空则设置deleteFlag
            Object deleteFlag = metaObject.getValue(DELETE_FLAG);
            if (ObjectUtil.isNull(deleteFlag)) {
                setFieldValByName(DELETE_FLAG, EnumUtil.toString(CommonDeleteFlagEnum.NOT_DELETE), metaObject);
            }
        } catch (ReflectionException ignored) { }
        try {
            //为空则设置createUser
            Object createUser = metaObject.getValue(CREATE_USER);
            if (ObjectUtil.isNull(createUser)) {
                setFieldValByName(CREATE_USER, this.getUserId(), metaObject);
            }
        } catch (ReflectionException ignored) { }
        try {
            //为空则设置createTime
            Object createTime = metaObject.getValue(CREATE_TIME);
            if (ObjectUtil.isNull(createTime)) {
                setFieldValByName(CREATE_TIME, DateTime.now(), metaObject);
            }
        } catch (ReflectionException ignored) { }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            //设置updateUser
            setFieldValByName(UPDATE_USER, this.getUserId(), metaObject);
        } catch (ReflectionException ignored) { }
        try {
            //设置updateTime
            setFieldValByName(UPDATE_TIME, DateTime.now(), metaObject);
        } catch (ReflectionException ignored) {
            ignored.printStackTrace();
        }
    }

    /**
     * 获取用户id
     */
    private String getUserId() {
        try {
            String loginId = StpUtil.getLoginIdAsString();
            if (ObjectUtil.isNotEmpty(loginId)) {
                return loginId;
            } else {
                return "-1";
            }
        } catch (Exception e) {
            return "-1";
        }
    }
}
